package com.yylending.las.authority.verifycode;

import android.text.TextUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.mvp.ResponseCode;
import com.yylending.las.Global;
import com.yylending.las.authority.rsa.RSAEncodePresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by HenryZhang on 2016/11/3.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class VerifyCodePresenter extends RSAEncodePresenter<Model, VerifyCodePresenter.View> {
	private final static String TAG = "VerifyCodePresenter";

	public static class Generator implements PresenterFactory<VerifyCodePresenter> {
		@Override
		public VerifyCodePresenter create() {
			return new VerifyCodePresenter();
		}
	}

	public interface View extends IView {
		void getVerifyCodeSuccess(String code);

		void getVerifyCodeFail(String msg);
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(VerifyCodePresenter.View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new VerifyCodeModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		return params;
	}

	public void verificationCode(String type, String phone, String operation, String seconds) {
		execute(new VerifyCodeModel.VerificationCode(type, phone, operation, seconds), VerifyCodeModel.METHOD_GET_VERIFY_CODE, false, null, mRequestPage);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getCodeResult(VerifyCodeModel.GetCodeResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			if (BaseResultEntity.isResponseSuccess(result)) {
				String code = "";
				mView.getVerifyCodeSuccess(code);
			} else {
				String msg = result.getRetMsg();
				if (ResponseCode.CODE_DECODE_FAIL.equalsIgnoreCase(result.getRetCode())) {
					Global.KEY_RSA = "";
					msg = "获取验证码失败，请重试";
				}
				if(TextUtils.isEmpty(msg)) msg = "获取验证码失败，请重试";
				mView.getVerifyCodeFail(msg);
			}
		}
	}
}
